package ink.lovejinhu.swardToOffer;

public class Offer_053_I {
    /**
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        if (nums.length==0) {
            return 0;
        }
        int left = 0;
        int right = nums.length-1;
        if ( target < nums[left]||target > nums[right] ) {
            return 0;
        }
        int mid=0;
        while (left <= right) {
            mid = left + right >> 1;
            if (nums[mid] == target) {
                break;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if (nums[mid] != target) {
            return 0;
        } else {
            left = mid - 1;
            right = mid + 1;
            int res = 1;
            while (left >= 0) {
                if (nums[left] == target) {
                    left--;
                    res++;
                } else {
                    break;
                }
            }
            while (right <= nums.length - 1) {
                if (nums[right] == target) {
                    right++;
                    res++;
                } else {
                    break;
                }
            }
            return res;
        }
    }
}
